/*
 * All rights Reserved, Designed By Yealink
 * Copyright (c) 2018/3/21 by Yealink
 *
 * @author yl1633
 * Createdate:  2018/3/21 14:07
 */
package com.xx.guava_cache;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author fanjj
 * @date 2018/3/21
 */
public class CacheLoaderTest {

    static LoadingCache<String, String> cache = CacheBuilder.newBuilder().refreshAfterWrite(3, TimeUnit.HOURS)// 给定时间内没有被读/写访问，则回收。
            .expireAfterAccess(1, TimeUnit.HOURS)// 缓存过期时间和redis缓存时长一样
            .maximumSize(1000)// 设置缓存个数
            .build(new CacheLoader<String, String>() {
                @Override
                /** 当本地缓存命没有中时，调用load方法获取结果并将结果缓存 **/
                public String load(String appKey) {
                    return getAppkeyInfo(appKey);
                }

                /** 数据库进行查询 **/
                private String getAppkeyInfo(String appKey) {
                    System.out.println("method<getAppkeyInfo> get AppkeyInfo form DB appkey<" + appKey + ">");
                    return "123";
                }
            });

    public static String getAppkeyInfoByAppkey(String appKey) {
        try {
            System.out.println("method<getAppkeyInfoByAppkey> appkey<" + appKey + ">");
            return cache.get(appKey);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] agrs) {
        CacheLoaderTest.getAppkeyInfoByAppkey("aaa");
        CacheLoaderTest.getAppkeyInfoByAppkey("aaa");
    }
}
